package com.example.javaee.service;

import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;
import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

@Service
public class ImageService {

    @Autowired
    UserMapper userMapper;

    String host;
    @Value("${server.port}")
    String post;
    String sonPath="/img/";

    private static final Logger logger = LoggerFactory.getLogger(ImageService.class);


    private void setUrl(Integer userId,String url){
        User user=userMapper.selectById(userId);
        user.setHeaderUrl(url);
        userMapper.updateById(user);
    }

    public String upload(Integer userId,MultipartFile file){
        //返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
        if (file.isEmpty()) {
            return "文件为空";
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        //获取本机IP
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("get server host Exception e:", e);
        }

        // 设置文件上传后的路径
        String filePath =System.getProperty("user.dir")+"/img/";
        logger.info("上传的文件路径" + filePath);
        logger.info("存入数据库的图片路径：" + fileName);
        File dest = new File(filePath + fileName);
        String imgPath = (host + ":" + post + sonPath + fileName);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);

            //将链接保存到user数据库的URL中
            setUrl(userId,fileName);
            return "上传成功";
        } catch (Exception e) {
            return "上传失败";
        }
    }


    public String getHeaderString(Integer userId) throws IOException
    {
        User user=userMapper.selectById(userId);
        if(user == null)
        {
            return "";
        }
        String projectPath = System.getProperty("user.dir");
        projectPath.replaceAll( "\\\\",   "\\\\\\\\ ");
        String filePath =  projectPath + "\\img\\" + user.getHeaderUrl();
        logger.info("文件路径 : " + filePath);
        InputStream in = new FileInputStream(new File(filePath));
        logger.info("文件地址 : " + in.toString());
        String str = imageToBase64ByStream(in);
        logger.info("base64 : " + str);
        return str;
    }


    public static String imageToBase64ByStream(InputStream in)
    {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
            Encoder encoder = Base64.getEncoder();
            String encode = encoder.encodeToString(data);
            return encode;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return null;
    }
}
